package com.share.common.utils;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class Md5Util {
    private static MessageDigest md5;
    private static MessageDigest sha1;

    static {
        try {
            md5 = MessageDigest.getInstance("MD5");
            sha1 = MessageDigest.getInstance("SHA-1");
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
    }


    /**
     * 对字符串进行加密
     */
    private static String encode(String originString, MessageDigest md) {
        if (originString != null) {
            byte[] originStringByte = originString.getBytes();
            return encode(originStringByte, md);
        }
        return null;
    }

    /**
     * 对数组进行加密
     */
    private static String encode(byte[] originStringByte, MessageDigest md) {
        if (originStringByte != null) {
            try {
                // 使用指定的字节数组对摘要进行最后更新，然后完成摘要计算
                byte[] results = md.digest(originStringByte);
                // 将得到的字节数组变成字符串返回
                return HexUtil.byte2hex(results);
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
        return null;
    }


    public static String encodeByMD5(String originString) {
        return encode(originString, md5);
    }

    public static String encodeByMD5(byte[] originStringByte) {
        return encode(originStringByte, md5);
    }

    public static String sha1(String originString) {
        return encode(originString, sha1);
    }

    public static String sha1(byte[] originStringByte) {
        return encode(originStringByte, sha1);
    }

    public static void main(String[] args) {//////////////TODO
        //		String key = "leige_bbtyx_leige";
        System.out.println(encodeByMD5("sunzn"));
    }
}